import datetime

from django.shortcuts import render
from rest_framework import status
from rest_framework.decorators import api_view
from rest_framework.response import Response
from django.core.paginator import Paginator
from django.db.models import Q

from .models import Area, Cinema
from .serializers import AreaListSerializer, CinemaListSerializer, CinemaSerializer
from .utils.data_time_util import generate_date_list
from order.models import Order


# Create your views here.


@api_view(['GET'])
def city_list(request):
    """城市区域列表接口"""
    try:
        # 获取查询参数
        hot = request.GET.get('hot', '')

        # 构建查询集
        areas = Area.objects.all()

        # 按是否热门筛选
        if hot:
            try:
                # is_hot_bool = hot.lower() == 'true'
                areas = areas.filter(hot=hot)
            except ValueError:
                pass

        # 序列化数据
        serializer = AreaListSerializer(areas, many=True)

        return Response({
            'state': 200,
            'msg': '操作成功',
            'data': serializer.data
        })

    except Exception as e:
        return Response({
            'state': 500,
            'msg': f'操作失败: {str(e)}',
            'data': None
        }, status=status.HTTP_500_INTERNAL_SERVER_ERROR)


@api_view(['GET'])
def area_detail(request, area_id):
    """城市区域详情接口"""
    try:
        area = Area.objects.get(area_id=area_id)
        serializer = AreaListSerializer(area)

        # 获取子区域信息
        son_areas = area.get_son_areas()
        son_serializer = AreaListSerializer(son_areas, many=True)

        # 获取父级区域信息
        parent_area = area.get_parent_area()
        parent_serializer = AreaListSerializer(parent_area) if parent_area else None

        response_data = serializer.data
        response_data['son_areas'] = son_serializer.data
        response_data['parent_area'] = parent_serializer.data if parent_serializer else None

        return Response({
            'state': 200,
            'msg': '操作成功',
            'data': response_data
        })

    except Area.DoesNotExist:
        return Response({
            'state': 404,
            'msg': '区域不存在',
            'data': None
        }, status=status.HTTP_404_NOT_FOUND)
    except Exception as e:
        return Response({
            'state': 500,
            'msg': f'操作失败: {str(e)}',
            'data': None
        }, status=status.HTTP_500_INTERNAL_SERVER_ERROR)


@api_view(['GET'])
def cinema_list(request):
    """影院列表接口 - 支持分页和筛选
    
    接口地址：/fsdy/cinema/index?pagenum=1&pagesize=10&area=220&price=
    
    参数说明：
    - pagenum: 页码，默认1
    - pagesize: 每页数量，默认10
    - area: 区域ID，0表示全国，220表示南京，321表示上海等
    - price: 价格筛选，可选
    - search: 搜索关键词，可选
    """
    try:
        # 获取查询参数
        pagenum = int(request.GET.get('pagenum', 1))
        pagesize = int(request.GET.get('pagesize', 10))
        area = request.GET.get('area', '')
        price = request.GET.get('price', '')
        search = request.GET.get('search', '')

        # 构建查询集
        cinemas = Cinema.objects.filter(state=1)

        # 按区域筛选
        if area and area != '0':
            try:
                area_id = int(area)
                # 支持具体城市查询
                if area_id == 220:  # 南京
                    cinemas = cinemas.filter(area_id=220)
                elif area_id == 321:  # 上海
                    cinemas = cinemas.filter(area_id=321)
                else:
                    # 其他城市
                    cinemas = cinemas.filter(area_id=area_id)
            except ValueError:
                pass
        # area=0 表示全国，不添加区域筛选

        # 按价格筛选
        if price:
            try:
                price_value = float(price)
                cinemas = cinemas.filter(avg_price__lte=price_value)
            except ValueError:
                pass

        # 按名称搜索
        if search:
            cinemas = cinemas.filter(
                Q(title__icontains=search) |
                Q(address__icontains=search)
            )

        # 分页处理
        paginator = Paginator(cinemas, pagesize)
        try:
            page_obj = paginator.page(pagenum)
        except:
            page_obj = paginator.page(1)

        # 序列化数据
        serializer = CinemaListSerializer(page_obj.object_list, many=True)

        # 构建响应数据
        response_data = {
            'state': 200,
            'msg': '操作成功',
            'data': {
                'total': cinemas.count(),
                'pagenum': pagenum,
                'pagesize': pagesize,
                'total_pages': paginator.num_pages,
                'list': serializer.data
            }
        }

        # 添加区域信息
        if area == '220':
            response_data['data']['area_info'] = {
                'area_id': 220,
                'area_name': '南京',
                'area_type': 'city'
            }
        elif area == '321':
            response_data['data']['area_info'] = {
                'area_id': 321,
                'area_name': '上海',
                'area_type': 'city'
            }
        elif area == '0':
            response_data['data']['area_info'] = {
                'area_id': 0,
                'area_name': '全国',
                'area_type': 'country'
            }

        return Response(response_data)

    except Exception as e:
        return Response({
            'state': 500,
            'msg': f'操作失败: {str(e)}',
            'data': None
        }, status=status.HTTP_500_INTERNAL_SERVER_ERROR)


@api_view(['GET'])
def cinema_detail(request, id):
    """影院详情接口"""
    try:
        cinema = Cinema.objects.get(id=id, state=1)
        serializer = CinemaSerializer(cinema)

        return Response({
            'state': 200,
            'msg': '操作成功',
            'data': serializer.data
        })

    except Cinema.DoesNotExist:
        return Response({
            'state': 404,
            'msg': '影院不存在',
            'data': None
        }, status=status.HTTP_404_NOT_FOUND)
    except Exception as e:
        return Response({
            'state': 500,
            'msg': f'操作失败: {str(e)}',
            'data': None
        }, status=status.HTTP_500_INTERNAL_SERVER_ERROR)


@api_view(['GET'])
def cinema_areas(request):
    """获取支持的城市区域列表"""
    try:
        # 从数据库获取热门城市
        hot_areas = Area.objects.filter(is_hot=True).order_by('sort', 'area_id')
        print(hot_areas)

        # 添加"全国"选项
        areas_data = [
            # {
            #     "area_id": 0,
            #     "area_name": "全国",
            #     "area_type": 0,
            #     # "area_type_display": "全国",
            #     "is_hot": True,
            #     "pinyin": "quanguo",
            #     "sort": -1
            # }
        ]

        # 添加数据库中的热门城市
        for area in hot_areas:
            areas_data.append({
                "area_id": area.area_id,
                "area_name": area.area_name,
                "parent_id": area.parent_id,
                "area_type": area.area_type,
                # "area_type_display": area.area_type_display,
                "agency_di": area.agency_di,
                "son_id": area.son_id,
                "is_hot": area.is_hot,
                "pinyin": area.pinyin,
                "sort": area.sort
            })

        return Response({
            'state': 200,
            'msg': '操作成功',
            'data': areas_data
        })

    except Exception as e:
        return Response({
            'state': 500,
            'msg': f'操作失败: {str(e)}',
            'data': None
        }, status=status.HTTP_500_INTERNAL_SERVER_ERROR)


@api_view(['GET'])
def time_list(request):
    try:
        return Response({
            'state': 200,
            'msg': '操作成功',
            'data': generate_date_list()
        })
    except Exception as e:
        return Response({
            'state': 500,
            'msg': f'操作失败: {str(e)}',
            'data': None
        }, status=status.HTTP_500_INTERNAL_SERVER_ERROR)


@api_view(['PUT'])
def update_cinema_seat(request):
    try:
        user = request.user
        seat = request.POST.get('seat')
        cinema_id = request.POST.get('cinemaId')
        film_id = request.POST.get('filmId')
        seatIndexId = request.POST.get('seatIndexId')
        is_seat_selected = True if request.POST.get('isSeatSelected') == 'true' else False
        print('cinema_id', cinema_id)
        print('film_id', film_id)
        print('is_seat_selected', is_seat_selected)

        cinema = Cinema.objects.get(id=cinema_id)
        cinema.seat = seat
        cinema.save()

        if is_seat_selected:
            Order.objects.create(cinema_id=cinema_id, film_id=film_id, user_id=user.id, cinema_index_id=seatIndexId)
        else:
            Order.objects.filter(cinema_id=cinema_id, film_id=film_id, user_id=user.id, cinema_index_id=seatIndexId).delete()

        # serializer = CinemaSerializer(cinema)

        return Response({
            'state': 200,
            'msg': '操作成功',
            'data': None
        })

    except Exception as e:
        return Response({
            'state': 500,
            'msg': f'操作失败: {str(e)}',
            'data': None
        }, status=status.HTTP_500_INTERNAL_SERVER_ERROR)
